package com.example.huixue.service;

import com.example.huixue.common.PageResult;
import com.example.huixue.entity.Favorite;
import com.example.huixue.mapper.FavoriteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FavoriteService {
    
    @Autowired
    private FavoriteMapper favoriteMapper;
    
    /**
     * 添加收藏
     */
    public Favorite addFavorite(Long userId, Long resourceId) {
        // 检查是否已经收藏过
        if (favoriteMapper.existsByUserAndResource(userId, resourceId)) {
            throw new RuntimeException("您已经收藏过这个资源了");
        }
        
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setResourceId(resourceId);
        favorite.setCreatedAt(LocalDateTime.now());
        
        int result = favoriteMapper.insert(favorite);
        if (result <= 0) {
            throw new RuntimeException("收藏失败");
        }
        
        return favorite;
    }
    
    /**
     * 取消收藏
     */
    public void removeFavorite(Long userId, Long resourceId) {
        int result = favoriteMapper.deleteByUserAndResource(userId, resourceId);
        if (result <= 0) {
            throw new RuntimeException("取消收藏失败");
        }
    }
    
    /**
     * 检查用户是否已收藏该资源
     */
    public boolean isFavorited(Long userId, Long resourceId) {
        return favoriteMapper.existsByUserAndResource(userId, resourceId);
    }
    
    /**
     * 获取用户收藏列表（分页）
     */
    public PageResult<Favorite> getUserFavorites(Long userId, int current, int size) {
        int offset = (current - 1) * size;
        
        List<Favorite> favorites = favoriteMapper.findByUserWithPagination(userId, offset, size);
        long total = favoriteMapper.countByUser(userId);
        
        return new PageResult<>(favorites, total, current, size);
    }
    
    /**
     * 获取用户收藏数量
     */
    public long getUserFavoriteCount(Long userId) {
        return favoriteMapper.countByUser(userId);
    }
    
    /**
     * 获取资源被收藏数量
     */
    public long getResourceFavoriteCount(Long resourceId) {
        return favoriteMapper.countByResource(resourceId);
    }
    
    /**
     * 获取最近收藏的资源
     */
    public List<Favorite> getRecentFavorites(Long userId, int limit) {
        return favoriteMapper.findRecentByUser(userId, limit);
    }
    
    /**
     * 根据ID获取收藏记录
     */
    public Favorite getFavoriteById(Long id) {
        return favoriteMapper.findById(id);
    }
} 